package com.tau.egonetwork.linkedin;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONObject;

import com.tau.egonetwork.common.Log;
import com.tau.egonetwork.exceptions.LinkedinAccessTokenException;
import com.tau.egonetwork.exceptions.LinkedinException;
import com.tau.egonetwork.exceptions.LinkedinThrottleLimitExceededException;
import com.tau.egonetwork.net.IExceptionHandler;

public class LinkedinExceptionHandler implements IExceptionHandler {

	private static final String LINKEDIN_ERROR_CODE = "errorCode";
	private static final String LINKEDIN_ERROR_MESSAGE = "message";
	
	@Override
	public void onException(Exception e, InputStream errorStream) throws Exception {
				
		if (errorStream != null) {
			
			BufferedReader readError = new BufferedReader(
			        new InputStreamReader(errorStream));
			String error;
			StringBuffer buffer = new StringBuffer();
	 
			while ((error = readError.readLine()) != null) {
				buffer.append(error);
			}
			readError.close();
									
			JSONObject json = null;
			try {
				json = new JSONObject(buffer.toString());
			} catch (Exception ex) {
				throw new LinkedinException(e);
			}
			
			if (json.has(LINKEDIN_ERROR_CODE)) {
				if (json.has(LINKEDIN_ERROR_MESSAGE)) {
					if (json.getString(LINKEDIN_ERROR_MESSAGE).contains("Throttle")) {
						throw new LinkedinThrottleLimitExceededException(e);
					} else if (json.getString(LINKEDIN_ERROR_MESSAGE).contains("access token")) {
						throw new LinkedinAccessTokenException(e);
					}
				}
			}
		}
		
		//if we got to here without throwing anything more specific:
		Log.writeExceptionToLog(e);
		throw new LinkedinException(e);
	}

}
